package cn.icatw.leetcode.editor.cn;
//给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
//
//
//
// 示例 1：
//
//
//输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出：[1,2,3,6,9,8,7,4,5]
//
//
// 示例 2：
//
//
//输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出：[1,2,3,4,8,12,11,10,9,5,6,7]
//
//
//
//
// 提示：
//
//
// m == matrix.length
// n == matrix[i].length
// 1 <= m, n <= 10
// -100 <= matrix[i][j] <= 100
//
//
// Related Topics 数组 矩阵 模拟 👍 1633 👎 0


import java.util.ArrayList;
import java.util.List;

//Java：螺旋矩阵
public class T54_SpiralMatrix {
    public static void main(String[] args) {
        Solution solution = new T54_SpiralMatrix().new Solution();
        // TO TEST
        //List<Integer> integers = solution.spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
        List<Integer> integers = solution.spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}});
        System.out.println(integers);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            //x-行
            int m = matrix.length;
            //y-列
            int n = matrix[0].length;
            int top = 0, bottom = m - 1, left = 0, right = n - 1;
            List<Integer> result = new ArrayList<>();
            Integer[] array = result.toArray(new Integer[0]);

            int num = 1;
            while (num <= m * n) {
                //    绕圈
                //    上边，从左往右
                for (int i = left; i <= right; i++) {
                    result.add(matrix[top][i]);
                    num++;
                }
                top++;
                //    右边，从上往下
                if (num > m * n){
                    break;
                }
                for (int i = top; i <= bottom; i++) {
                    result.add(matrix[i][right]);
                    num++;
                }
                right--;
                //    下边，从右往左
                if (num > m * n){
                    break;
                }
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                    num++;
                }
                bottom--;
                //    左边，从下往上
                if (num > m * n){
                    break;
                }
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                    num++;
                }
                left++;
            }
            return result;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
